﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.ExtNet;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;

using PartialViewResult = Ext.Net.MVC.PartialViewResult;

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    [AutomaticTemplate]
    public class OrgController : Controller
    {
        public ActionResult Index(string containerId)
        {
            if (containerId.IsNullOrEmpty())
            {
                return View(new OrgIndexViewModel());
            }
            else
            {
                return new PartialViewResult
                {
                    //ViewName = "Index",
                    Model = new OrgIndexViewModel(),
                    ContainerId = containerId,
                    RenderMode = RenderMode.AddTo
                };
            }
        }

        public async Task<StoreResult> GetTreeData(string node)
        {
            var leftTree = new Node()
            {
                Text = "根节点",
                NodeID = "Root",
                Expanded = true,
                Leaf = true,
                Checked = null
            };
            IEnumerable<OrgDTO> list;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                list = await proxy.Channel.GetOrgsWithCount();
            }
            var builder = new TreeBuilder<Guid, OrgDTO>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Text = p.Title;
                    treeNode.NodeID = p.Id.ToString();
                    treeNode.AttributesObject = p;
                    treeNode.Leaf = list.All(x => x.ParentId != p.Id);
                    if (!treeNode.Leaf)
                        treeNode.Icon = Icon.Folder;
                    treeNode.Expanded = true;
                }
            };

            builder.Build(list, leftTree, null);

            return this.Store(leftTree.Children);
        }

        public ActionResult MoveOrSort(MoveOrSortInfo info)
        {
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var res = proxy.Channel.OrgMoveOrSort(info.ParentId, info.Ids);

                return this.JsonNet(res);
            }
        }

        public async Task<ActionResult> Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            OrgDTO dto;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                dto = proxy.Channel.GetOrgInfo(id.Value);
            }
            if (dto == null)
            {
                return HttpNotFound();
            }
            var vm = dto.To<OrgViewModel>();
            vm.OrgTree = await OrgTree();

            return new PartialViewResult { Model = vm };
        }

        public async Task<ActionResult> Create()
        {
            var vm = new OrgViewModel();
            vm.OrgTree = await OrgTree();
            return new PartialViewResult { Model = vm };
        }

        public async Task<ActionResult> Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            OrgDTO dto;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                dto = proxy.Channel.GetOrgInfo(id.Value);
            }
            if (dto == null)
            {
                return HttpNotFound();
            }
            var vm = dto.To<OrgViewModel>();
            vm.OrgTree = await OrgTree();

            return new PartialViewResult { Model = vm };
        }

        [System.Web.Mvc.HttpPost]
        public ActionResult Save(OrgViewModel org)
        {
            OrgDTO dto = org.To<OrgDTO>();

            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var res = proxy.Channel.SaveOrg(dto);
                return this.JsonNet(res);
            }
        }


        [System.Web.Mvc.HttpPost]
        public ActionResult Delete(Guid[] ids)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                res = proxy.Channel.DeleteOrgs(ids);
            }

            return this.JsonNet(res);
        }

        public static async Task<Node> OrgTree()
        {
            var leftTree = new Node()
            {
                Text = ".",
                NodeID = "Root",
                Expanded = true,
                AutoDataBind = false,
                Checked = null
            };
            IEnumerable<OrgDTO> list;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                list = await proxy.Channel.GetOrgs();
            }
            var builder = new TreeBuilder<Guid, OrgDTO>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Text = p.Title;
                    treeNode.NodeID = p.Id.ToString();
                    treeNode.AutoDataBind = false;
                    treeNode.Leaf = list.All(x => x.ParentId != p.Id);
                    treeNode.Expanded = true;
                }
            };

            builder.Build(list, leftTree, null);

            return leftTree;
        }

    }
}
